import UserServices from '@/services/user';
import { requestSuccess, getMastId } from '@/utils/tools';
import { Router, Route } from 'dva/router';
import queryString from 'query-string';
import { Toast } from 'antd-mobile';
import { apiMaps } from '@/utils/maps';
import {
  deviceReady
} from '@/utils/cordova';

import CViewApplication from '@/routes/detail/cViewApplication';
import CTravelDetails from '@/routes/detail/cTravelDetails';
import CActualTravelDetails from '@/routes/detail/cActualTravelDetails';
import CPurposeOfTripAndRemark from '@/routes/detail/cPurposeOfTripAndRemark';
import CTicketInfo from '@/routes/detail/cTicketInfo';
import CAccommodationInfo from '@/routes/detail/cAccommodationInfo';
import CAccountingPostingRelated from '@/routes/detail/cAccountingPostingRelated';
import CReimbursementDetails from '@/routes/detail/cReimbursementDetails';
import CReimbursableAmount from '@/routes/detail/cReimbursableAmount';
import CAttachments from '@/routes/detail/cAttachments';
import CProcessLog from '@/routes/detail/cProcessLog';
import CTravelRequestInfo from '@/routes/detail/cTravelRequestInfo';
import CBankInfo from '@/routes/detail/cBankInfo';
import CAdvanceInfo from '@/routes/detail/cAdvanceInfo';
import CComments from '@/routes/detail/cComments';
import CSapAccountDocNo from '@/routes/detail/cSapAccountDocNo';
import CCurrentOwner from '@/routes/detail/cCurrentOwner';

const allComponents = [{
  title: 'View Application',
  key: 'ViewApplication',
  path: CViewApplication,
},{
  title: 'Travel Request Info',
  key: 'TravelRequestInfo',
  path: CTravelRequestInfo
},{
  title: 'Travel Details',
  key: 'TravelDetails',
  path: CTravelDetails,
},{
  title: 'Actual Travel Details',
  key: 'ActualTravelDetails',
  path: CActualTravelDetails,
},{
  title: 'Advance Info',
  key: 'AdvanceInfo',
  path: CAdvanceInfo
},{
  title: 'Ticket Info',
  key: 'TicketInfo',
  path: CTicketInfo
},{
  title: 'Accommodation Info',
  key: 'AccommodationInfo',
  path: CAccommodationInfo
},{
  title: 'Bank Info',
  key: 'BankInfo',
  path: CBankInfo
},{
  title: 'Reimbursement Details',
  key: 'ReimbursementDetails',
  path: CReimbursementDetails
},{
  title: 'Purpose Of Trip & Other Qusetions/Remark',
  key: 'PurposeOfTripAndRemark',
  path: CPurposeOfTripAndRemark
},{
  title: 'Attachments',
  key: 'Attachments',
  path: CAttachments
},{
  title: 'Accounting Posting Related',
  key: 'AccountingPostingRelated',
  path: CAccountingPostingRelated
},{
  title: 'Reimbursable Amount',
  key: 'ReimbursableAmount',
  path: CReimbursableAmount
},{
  title: 'Comments',
  key: 'Comments',
  path: CComments,
},{
  title: 'SAP Account Document No',
  key: 'SapAccountDocNo',
  path: CSapAccountDocNo,
},{
  title: 'Process Log',
  key: 'ProcessLog',
  path: CProcessLog,
},{
  title: 'Current Owner',
  key: 'CurrentOwner',
  path: CCurrentOwner,
}]

const transComponentsByKeys = (showKeys, editKeys, extraEditArr) => {
  let arr = [];
  for(let i in allComponents){
    const item = allComponents[i];
    if(showKeys.indexOf(item.key) !== -1){
      const newItem = {...item};
      newItem.index = parseInt(i);
      if(editKeys.indexOf(item.key) !== -1){
        // 显示 且 编辑状态
        newItem.edit = true;
      }
      newItem.extraEditArr = extraEditArr;
      arr.push(newItem);
    }
  }
  arr = global._.chain(arr).uniqBy('key').sortBy('index').valueOf();

  return arr;
}

const requestMastReadComponents = (mast) => {
  // 一个集合 对应 requestMastRead.ftl;
  let arr = [];
  arr = arr.concat(['ViewApplication', 'TravelDetails']);
  if(["Report Internal Manager Approvel","GM Guardian","Report Project Manager Approvel","CFO Approvel","CEO Approvel","Finish Travel Report","Report Rejected","Accounting Approvel","Closed"].indexOf(mast.status) !== -1){
    arr = arr.concat(['TicketInfo', 'AccommodationInfo', 'ReimbursementDetails']);
  }
  return arr;
}

const getComponentsByData = (actionType, data) => {
  let arr = [];
  let showArr = [];//显示的组件
  let editArr = [];//可编辑的组件
  let extraEditArr = [];//可编辑的组件中更细致的控制，如TravelDetails中的UpdateWbsCode
  const mast = data.mast;
  switch (actionType) {
    case 'viewWorkflowEntry' :
    showArr = showArr.concat(requestMastReadComponents(mast));
    if(mast.status == 'CEO Approvel' || mast.status == 'CFO Approvel' || mast.status == 'GM Guardian' || mast.status == 'Rejected' || 'Finish Travel Report' == mast.status || 'Report Rejected'==mast.status || 'Report Internal Manager Approvel' == mast.status){
      showArr.push('ActualTravelDetails');
    }
    if(data.showAction){
      if('Report Special Finance Approvel' == mast.status){
        showArr = showArr.concat(['TicketInfo', 'ActualTravelDetails', 'AccommodationInfo', 'ReimbursementDetails']);
      }
      if('Request Rejected' == mast.status){
        showArr.push('PurposeOfTripAndRemark');
        editArr = editArr.concat(['PurposeOfTripAndRemark', 'TravelDetails']);
      }
      if('Finish Travel Report' == mast.status || 'Report Rejected'== mast.status){
        editArr = editArr.concat(['TicketInfo', 'ReimbursementDetails']);
        //临时修改
        editArr = editArr.concat(['ActualTravelDetails', 'AccommodationInfo'])
      }
      if('Special Finance Approvel' == mast.status){
        extraEditArr = extraEditArr.concat(['UpdateWbsCode']);
      }
      showArr.push('Comments');
    }else{
      if(['Report Internal Manager Approvel','GM Guardian','Report Project Manager Approvel','CFO Approvel','CEO Approvel','Finish Travel Report','Report Rejected','Accounting Approvel','Accounting Consult','Closed'].indexOf(mast.status) !== -1){
        showArr.push('ReimbursementDetails');
      }
    }
    break;
    case 'viewWorkflowEntryAdv' :
      showArr = showArr.concat(['TravelRequestInfo', 'AdvanceInfo', 'BankInfo']);
      if(data.showAction){
        showArr.push('Comments');
      }
    break;
    case 'viewUpdateForm' :
      showArr = showArr.concat(['ViewApplication', 'TravelDetails', 'PurposeOfTripAndRemark']);
      if( mast.status=='Request Rejected' || "Draft"== mast.status){
        // advanceInfo edit 与 Traveller Detail 在一起了
        editArr = editArr.concat(['TravelDetails', 'PurposeOfTripAndRemark']);
      }
    break;
    // viewUpdateAdvanceInWorkFlow、viewUpdateRequestInWorkFlow
    // 两个类型都跳过preview posting状态，这样都要多请求一个接口以获取提交按钮，
    // 是因为['ReimbursableAmount', 'AccountingPostingRelated']暂不用编辑
    case 'viewUpdateAdvanceInWorkFlow':
      // showArr = showArr.concat(['TravelRequestInfo','ActualTravelDetails', 'AdvanceInfo', 'BankInfo', 'AccountingPostingRelated', 'ReimbursableAmount', 'Comments']);
      showArr = showArr.concat(['TravelRequestInfo', 'AdvanceInfo', 'BankInfo', 'AccountingPostingRelated', 'ReimbursableAmount', 'Comments']);
      // editArr = editArr.concat(['ReimbursableAmount', 'AccountingPostingRelated']);
      // 财务逻辑复杂，有BUG，先只做展现
    break;
    case 'viewUpdateRequestInWorkFlow':
      showArr = showArr.concat(requestMastReadComponents(mast));
      showArr = showArr.concat(['Reimbursement','ActualTravelDetails', 'AccountingPostingRelated', 'Comments', 'SapAccountDocNo'])
    break;
  }
  // 页脚必有
  showArr = showArr.concat(['ProcessLog', 'CurrentOwner']);
  // 转换状态
  arr = transComponentsByKeys(showArr, editArr, extraEditArr);
  console.log(arr);
  return arr;
}

const getExtraInfoByActionType = (detail, actionType) => {
  if(actionType == 'viewUpdateForm'){
    detail.mobileAvailableActions = detail.mobileAvailableActions.concat([{
        id: 'saveDraft',
        name: 'Save Draft'
      },{
        id: 'submit',
        name: 'Submit'
      }])
    detail.mobileAvailableActions = global._.uniqBy(detail.mobileAvailableActions, 'name');
  }
  // 转换
  detail.mast.needAdvance = detail.mast.needAdvance == 'YES' ? true:false;
  detail.mast.needReimbursement = detail.mast.needReimbursement == 'YES' ? true:false;
  detail.mast.subCompanys = detail.mast.subCompanys && global._.isString(detail.mast.subCompanys) ? detail.mast.subCompanys.split(', '):[];
  detail.mast.subCompanysChange = detail.mast.subCompanysChange && global._.isString(detail.mast.subCompanysChange) ? detail.mast.subCompanysChange.split(', '):[];

  return detail;
}

const INIT_STATE = {
  showComponents: [],
  detail: {
    mobileAvailableActions: [],
    mast: {
      needAdvance: false,
      requestorRemarks: '',
      expDptrDayStatus: 'Start of Work day',
      expRtnDayStatus: 'Middle of work day',
      dptrDay: '',
      rtnDay: '',
      expDptrDayStatusChange: '',
      expRtnDayStatusChange: '',
      dptrDayChange: '',
      rtnDayChange: '',
      subCompanysChange: [],
      citiesChange: [],
      cities: [],
      purpose: '',
      type: 'Others',
      remark: ''
    }
  }
}

let URL_SERACH = '';

export default {

  namespace: 'detail',

  state: {
    ...INIT_STATE
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({pathname, search}) => {
        URL_SERACH = search;
        // const query1 = queryString.parse(window.location.search);
        // console.log(query1);
        // console.log(pathname);
        if (pathname === '/detail') {
          Toast.loading('Loading...', 0);
          deviceReady().then(() => {
            dispatch({type: 'init'})
            dispatch({type: 'getData'});
          }).catch(e => {
            dispatch({type: 'init'})
            dispatch({type: 'getData'});
          });
        }
      })
    },
  },

  effects: {
    *getExtraBtnsOfActionType({ payload }, { call, put, select }){
      const detail = yield select(({detail}) => detail.detail);
      const query = queryString.parse(URL_SERACH);
      let isAdv = false;
      let id = {};
      if(detail.advMast){
        id.advMastId = query.id;
        isAdv = true;
      }else{
        id.trsMastId = query.id;
      }
      const actionName = isAdv ?'perviewRequestPostingAdv': 'perviewRequestPosting';
      const mapOrsVats = global._.map(detail.mast.orsVats, item => {
        return {
          SGTXT: item.sGTXT,
          WRBTR_SDISP: item.wRBTR_SDISP,
          WRBTR_H: item.wRBTR_H,
          PRCTR: item.pRCTR,
          taxRMB: item.taxRmb,
          itemText: ''
        }
        // if(isAdv){
        // }else{
        //   return {
        //   }
        // }
      })
      console.log(id);
      const result = yield call(UserServices.getExtraBtnsOfActionType, {
        ...id,
        [Object.keys(id)[0].split('Id')[0]] : {//trsMast or advMast
          BUDAT: global.moment(detail.mast.bUDAT).format('YYYY-MM-DD'),
          BLDAT: detail.mast.bLDAT
        },
        '': mapOrsVats
      }, actionName);
      if(requestSuccess(result)){
        yield put({
          type: 'save',
          payload: {
              detail: {
                ...detail,
                mobileAvailableActions: result.data.mobileAvailableActions
              },
            }
        });
      }
    },
    *getData({ payload }, { call, put, select }){
      const detailDefault = yield select(({ detail }) => detail.detail);
      const {id, actionType} = queryString.parse(URL_SERACH);

      const target = global._.find(apiMaps, item => {
        return item.actionType == actionType;
      });
      const result = yield call(UserServices.getDetailData, {action: target.actionType, query: `${target.query}=${id}`})
      if(requestSuccess(result)){
        let detail = {
          ...detailDefault,
          ...result.data,
          mast: {
            ...detailDefault.mast,
            ...result.data.trsMast,
            ...result.data.advMast
          }
        }
        detail = getExtraInfoByActionType(detail, actionType);
        if(result.data.trsMast){
          detail.copyActualDetail = {//用于对比被改变的值，提示填写理由
            cities: result.data.trsMast.cities || [],
            dptrDay: result.data.trsMast.dptrDay || '',
            expDptrDayStatus: result.data.trsMast.expDptrDayStatus || '',
            rtnDay: result.data.trsMast.rtnDay || '',
            expRtnDayStatus: result.data.trsMast.expRtnDayStatus || '',
            type: result.data.trsMast.type || '',
            subCompanys: detail.mast.subCompanys || '',
            purpose: result.data.trsMast.purpose || ''
          }
        }

        yield put({
          type: 'save',
          payload: {
              showComponents: getComponentsByData(actionType, detail),
              detail,
            }
        });
        // 额外处理，获取按钮
        if(actionType == 'viewUpdateAdvanceInWorkFlow' || actionType == 'viewUpdateRequestInWorkFlow'){
          yield put({type: 'getExtraBtnsOfActionType'});
        }
        console.log(123);
      }
    },
    *saveViewWorkflowEntry({ payload }, { call, put, select }){
      // 报销金额模块，先人后保存详情，才可以拿到对应人的银行卡信息
      const detail = yield select(({ detail }) => detail.detail);
      const {id, actionType} = queryString.parse(URL_SERACH);
      const result = yield call(UserServices.saveViewWorkflowEntry, {
        trsMastId: id,
        trsMast:{
          citiesChange: detail.mast.citiesChange,
          dptrDayChange: detail.mast.dptrDayChange,
          expDptrDayStatusChange: detail.mast.expDptrDayStatusChange,
          rtnDayChange: detail.mast.rtnDayChange,
          expRtnDayStatusChange: detail.mast.expRtnDayStatusChange,
          typeChange: detail.mast.typeChange,
          purposeChange: detail.mast.purposeChange,
          needReimbursement: detail.mast.needReimbursement?'YES':'NO',
          payee: detail.mast.payee,
          accountHolder: detail.mast.accountHolder,
          bankAccount: detail.mast.bankAccount,
          bankName: detail.mast.bankName,
          consultOwner: detail.mast.consultOwner,
          remark: detail.mast.remark
        }
      });
      if(requestSuccess(result)){
        yield put({type: 'getData'});
      }

    }
  },

  reducers: {
    init(state, action){
      return {...state, ...INIT_STATE};
    },
    changeMast(state, {payload}) {
      return { ...state, detail: {
        ...state.detail,
        mast: {
          ...state.detail.mast,
          ...payload
        }
      }};
    },
    changeDetail(state, {payload}) {
      return { ...state, detail: {
        ...state.detail,
        ...payload
      }};
    },
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },

};
